//const mongoose = require('mongoose');
//var User = mongoose.model('client');


exports.getCart = function (req, res) {
    //数据:
    //req.session.carts = { '1': [ { _id: "57bd57a6a23725d0f2c7f572", num: 2 }, { _id: "57bd57a6a23725d0f2c7f572", num: 2 } ] };
    //var carts = {};
    var cartItem = [];
    if(req.session.client){
        var carts = req.session.client.cart;
        if (req.session.client.cart) {
            carts = req.session.client.cart;
            var mid = req.params.mid;
            cartItem = carts[mid];
            if (cartItem) {
                res.json({carts: cartItem, msg: "SUCCESS"});
            } else {
                res.json({msg: "error"});
            }
        } else {
            res.json({msg: "error"});
        }
    } else {
        res.json({msg : 'error'})
    }
};

exports.addCart = function (req, res) {
    var carts = {};
    var cartItem = [];
    var mid = req.params.mid;
    var did = req.body.did;
    var num = req.body.num;
    if (req.session.client) {
        if (req.session.client.cart) {
            carts = req.session.client.cart;
            if (carts[mid]) {
                cartItem = carts[mid];
            }
        }
        cartItem.push({did: did, num: num});
        carts[mid] = cartItem;
        req.session.client.cart = carts;
        res.json({msg: "SUCCESS"})
    } else {
        res.json({msg: "error"})
    }

};

exports.updateCart = function (req, res) {
    var carts = {};
    var cartItem = [];
    if (req.session.client) {
        carts = req.session.client.cart;
        var mid = req.params.mid;
        var did = req.body.did;
        var num = req.body.num;
        cartItem = carts[mid];
        cartItem.forEach(function (c) {
            if (c.did == did) {
                c.num = num;
            }
            if (c.num == 0) {
            }
        });
        carts[mid] = cartItem;
        req.session.client.cart = carts;
        res.json({msg: "SUCCESS"});
    } else {
        res.json({msg: "error"})
    }
};